﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using BitwiseOre.SharedMemory.Core.Common;
using BitwiseOre.SharedMemory.JetBrains;

namespace BitwiseOre.SharedMemory.Core.IPCQueues
{
    [UsedImplicitly]
    internal sealed class ListenerQueueFactory: ISharedFactory<ListenerQueue>, ISharedObjectInit
    {
        public delegate IGuidQueue CreateGuidQueue(int count);

        public delegate IGuidQueue OpenGuidQueue();

        private readonly Func<int, int, ISemaphore> _createSemaphore;
        private readonly CreateGuidQueue _createGuidQueue;
        private readonly OpenSemaphore _openSemaphore;
        private readonly OpenGuidQueue _openGuidQueue;
        private readonly IListenerQueueConfig _config;

        private bool _createNew;

        public ListenerQueueFactory(ISemaphoreFactory semaphoreFactory, CreateGuidQueue createGuidQueue,
                                    OpenSemaphore openSemaphore, OpenGuidQueue openGuidQueue,
                                    IListenerQueueConfig config)
        {
            _createSemaphore = (initial, max) => semaphoreFactory.Create(initial,max);
            _config = config;
            _openGuidQueue = openGuidQueue;
            _openSemaphore = openSemaphore;
            _createGuidQueue = createGuidQueue;
        }

        public void InitializeNew()
        {
            _createNew = true;
        }

        public void InitializeExisting()
        {
            _createNew = false;
        }

        public ListenerQueue Create()
        {
            ISemaphore semaphore;
            IGuidQueue queue;

            // Create or open the dependencies in the opposite order to avoid a race condition
            if (_createNew)
            {
                queue = _createGuidQueue(_config.Count);
                semaphore = _createSemaphore(0, _config.Count);
            }
            else
            {
                semaphore = _openSemaphore();
                queue = _openGuidQueue();
            }
            return new ListenerQueue(semaphore, queue);
        }
    }
}